package com.example.gokuplayalong.bases.custom;


import com.example.gokuplayalong.bases.exception.ExceptionUtils;
import com.example.gokuplayalong.bases.threadpool.CustomThreadPoolExecutor;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.nio.file.Files;
import java.util.Base64;

public class CustomImageUtils {

    public static String encodeImageToBase64(File file) {
        InputStream in = null;
        byte[] data = null;

        //读取图片字节数组
        try {
            in = Files.newInputStream(file.toPath());
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Base64.getEncoder().encodeToString(data);

    }

    public static void urlToLocalImage(String url, String filename, String filenamesubx, File directory, CustomImageUtilsInterface customImageUtilsInterface) {


        CustomThreadPoolExecutor.getInstance().execute(new Runnable() {
            @Override
            public void run() {
                File file = new File(directory, filename + filenamesubx);
                URL urlfile;
                InputStream inputStream = null;
                OutputStream outputStream = null;
                try {
                    file.createNewFile();
                    //下载
                    urlfile = new URL(url);
                    inputStream = urlfile.openStream();
                    outputStream = new FileOutputStream(file);

                    int bytesRead = 0;
                    byte[] buffer = new byte[8192];
                    while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
                        outputStream.write(buffer, 0, bytesRead);
                    }
                } catch (Exception e) {
                    ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                } finally {
                    try {
                        if (null != outputStream) {
                            outputStream.close();
                        }
                        if (null != inputStream) {
                            inputStream.close();
                        }

                    } catch (Exception e) {
                        ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                    }
                }
                customImageUtilsInterface.CustomImageUtils(file);

            }
        });

    }

}
